
/**
 * 批量请求函数
 * @param {Array} urls 批量请求的地址
 * @param {Number} max 最大并发数
 * @param {Function} cb 回调函数
 */
function multipleRequest(urls, max, cb) {
  const length = urls.length;
  let finish = 0;
  const results = [];
  
  function fetchHandle(url, index) {
    fetch(url).then((res) => {
      finish++;
      results[index] = res;
      requestHandle();
    }).catch((err) => {
      finish++;
      results[index] = err;
      requestHandle();
    });
  }
  
  function requestHandle() {
    if (urls.length) {
      const url = urls.shift();
      fetchHandle(url, length - urls.length - 1);
    }
    if (finish >= length) {
      cb(results);
    }
  }

  for (let index = 0; index < max; index++) {
    requestHandle();
  }
}

/**
 * 简单模拟 fetch 请求
 * @param {string} url 
 */
function fetch(url) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`请求成功了,${url}`)
    }, 3000)
  })
}

// 测试-------------------
const urls = Array.from({ length: 10 }, (v, k) => `mock-url-${k}`);
console.log(urls)

multipleRequest(urls, 4, (res) => {
  console.log(res)
})